﻿app.factory('MovieFactory', ['$http', '$q', function ($http, $q) {
    var movies = [];

    var getAllMovies = function () {
        var deferred = $q.defer();
        $http({
            method: 'GET',
            url: '/api/apiMovies',
            contentType: 'application/json'
        }).success(function (data) {
            deferred.resolve(data);
        }).error(function (data) {
            deferred.reject(data);
        });
        return deferred.promise;
    };

    var createMovie = function (movie) {
        var deferred = $q.defer();
        $http({
            method: 'POST',
            url: '/api/apiMovies',
            data: movie,
            contentType: 'application/json'
        }).success(function (data) {
            movie.MovieId = data;
            movies.push(movie);
            deferred.resolve();
        }).error(function (data) {
            deferred.reject(data);
        });
        return deferred.promise;
    };

    var deleteMovie = function (id) {
        var deferred = $q.defer();
        $http({
            method: 'DELETE',
            url: '/api/apiMovies/' + id
        }).success(function (data) {
            for (var i = 0; i < movies.length; i++) {
                if (movies[i].MovieId == id) {
                    movies.splice(i, 1);
                    break;
                }
            }
            deferred.resolve(data);
        }).error(function (data) {
            deferred.reject(data);
        });
        return deferred.promise;
    };

    getAllMovies().then(function (data) {
        for (var i = 0; i < data.length; i++) {
            movies.push(data[i]);
        }
    });

    return {
        movies: movies,
        createMovie: createMovie,
        deleteMovie: deleteMovie
    }
}]);